    /*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.exception.BizException;
import me.zhengjie.modules.shop.domain.ProductKind;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.shop.service.ProductKindService;
import me.zhengjie.modules.shop.domain.vo.ProductKindQueryCriteria;
import me.zhengjie.modules.shop.mapper.ProductKindMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

import static me.zhengjie.modules.biz.domain.enums.ErrorCode.PRODUCT_KIND_ALREADY_EXIST;

    /**
* @description 服务实现
* @author yiwei.he
* @date 2024-04-11
**/
@Service
@RequiredArgsConstructor
public class ProductKindServiceImpl extends ServiceImpl<ProductKindMapper, ProductKind> implements ProductKindService {

    private final ProductKindMapper productKindMapper;

    @Override
    public PageResult<ProductKind> queryAll(ProductKindQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(productKindMapper.findAll(criteria, page));
    }

    @Override
    public List<ProductKind> queryAll(ProductKindQueryCriteria criteria){
        return productKindMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ProductKind resources) throws BizException {
        // 查询该商品是否已存在
        checkProductKind(resources);
        // 如果商品不存在，则添加商品
        if (checkProductKind(resources)) {
            resources.setCreateTime(LocalDateTime.now());
            save(resources);
        } else {
            // 商品已存在，抛出异常
            throw new BizException(PRODUCT_KIND_ALREADY_EXIST.getCode(), PRODUCT_KIND_ALREADY_EXIST.getMessage());
        }
    }

    /**
     * 检查商品种类是否存在
     * @param resources
     * @return
     */
    private boolean checkProductKind(ProductKind resources) {
        QueryWrapper<ProductKind> query = new QueryWrapper<>();
        query.eq("p_id", resources.getPId())
                .eq("specification", resources.getSpecification());
        ProductKind existingProductKind = productKindMapper.selectOne(query);
        return existingProductKind == null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProductKind resources) throws BizException {
        // 检查该商品是否存在
        if(checkProductKind(resources)){
            ProductKind productKind = getById(resources.getId());
            productKind.copy(resources);
            saveOrUpdate(productKind);
        } else {
            // 商品已存在，抛出异常
            throw new BizException(PRODUCT_KIND_ALREADY_EXIST.getCode(), PRODUCT_KIND_ALREADY_EXIST.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<ProductKind> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProductKind productKind : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品id", productKind.getPId());
            map.put("规格", productKind.getSpecification());
            map.put("单价", productKind.getPrice());
            map.put("图片", productKind.getImg());
            map.put("已售", productKind.getSold());
            map.put("库存", productKind.getStock());
            map.put("创建时间", productKind.getCreateTime());
            map.put("说明", productKind.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}